package com.milo.coding.jmm;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author milo
 * @Date 2021-01-18 17:34:24
 * @description: -server -Xcomp -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -XX:CompileCommand=compileonly,*Jmm03_CodeVisibility.refresh
 *
 *      -Djava.compiler=NONE  关闭jit 即时编译
 **/
@Slf4j
public class Jmm03_CodeVisibility {
    // 可见性
    // volatile 保证了及时可见

    // private volatile static boolean initFlag = false;
    private static boolean initFlag = false;

    /**
     * 当选择15行，运行发现选20行和选22行的运行效果是一样的
     * 还有各种草泥马的情况，
     */
    // private volatile static int counter = 0;
    private static int counter = 0;
    // private static Integer counter = 0;

    public static void refresh(){
        log.info("refresh data.......");
        initFlag = true;
        log.info("refresh data success.......");
    }

    public static void main(String[] args){
        Thread threadA = new Thread(()->{
            while (!initFlag){
                System.out.println("runing");
                // counter++;
            }
            log.info("线程：" + Thread.currentThread().getName()
                    + "当前线程嗅探到initFlag的状态的改变");
        },"threadA");
        threadA.start();

        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Thread threadB = new Thread(()->{
            refresh();
        },"threadB");
        threadB.start();
    }
}
